<template>
  <div class="ind-post-view">
    <div v-if="isSecretInd">
      <div class="secret-view">
        <span class="label">是否涉密：</span>
        <el-radio-group v-if="!hasSecretResult" v-model="isSecret" :disabled="secretDisabled" @change="saveFormAuto">
          <el-radio :label="false">否</el-radio>
          <el-radio :label="true">是</el-radio>
        </el-radio-group>
        <span v-else>{{ (isSecret && '是') || '否' }}</span>
        <span v-if="isSecret" class="tips">涉密指标需线下提交纸质证明材料！</span>
        <el-tooltip
          v-if="isSecret && rollbackable && hasSecretResult"
          class="item"
          effect="dark"
          content="点击撤回本次填报"
          placement="top">
          <i class="iconfont kh-return" @click="rollbackSecretIndPost"></i>
        </el-tooltip>
      </div>
      <div class="post-btn-view" v-if="isSecret && !hasSecretResult">
        <el-button size="small" @click="saveFormData(false)">暂存</el-button>
        <el-button type="primary" size="small" @click="saveFormData(true)">提交</el-button>
      </div>
    </div>
    <template v-if="!isOtherRelateInShare && !isSecret">
      <post-form
        :list="displayList"
        :pushable="pushable"
        :rollbackable="rollbackable"
        @form-change="saveFormAuto"
        @item-save="saveFormData"
        @rollback="refreshRelate => $emit('rollback', refreshRelate)"></post-form>
    </template>
    <div v-else-if="isOtherRelateInShare" class="inshare-tips">{{ inShareTips }}</div>
  </div>
</template>

<script>
import {
  saveIndPushDataBatch,
  saveIndPushDataTempBatch,
  listProvincialOrgan,
  rollbackIndPost,
} from '@api/modules/indication'

import { cloneDeep } from 'lodash'
import { formatDate, guid, parseJsonStr } from '@utility/utility'
import { INDICATION_STATUS, IND_POST_TYPE } from '@utility/dict'
import PostForm from './postForm/index.vue'

export default {
  name: 'IndPostView',
  components: { PostForm },
  props: {
    details: {
      type: Object,
    },
    pushable: {
      type: Boolean,
    },
  },
  data() {
    return {
      displayList: null,
      formValid: {
        scope: 'all', // form校验范围
        check: false,
      },
      // showSubmitBtns: false, // 统一提交按钮
      isRelateInd: false, // 是否是关联指标，关联指标整体推送
      postData: null,
      linkLabelWidth: 100,
      STATUS_TAG: INDICATION_STATUS._tag,
      isOtherRelateInShare: false,
      isSecret: false,
      hasSecretResult: false,
      secretDisabled: false,
    }
  },
  provide() {
    return {
      formValid: this.formValid,
    }
  },
  filters: {
    statusDisplay(val) {
      return INDICATION_STATUS[val]
    },
  },
  computed: {
    multipleMax() {
      if (this.details) {
        return (this.details.multipleMax && Number(this.details.multipleMax)) || null
      }
      return null
    },
    multipleMin() {
      if (this.details) {
        return (this.details.multipleMin && Number(this.details.multipleMin)) || 1
      }
      return null
    },
    // 内部展示push 按钮
    showPushInner() {
      return this.pushable && this.isOrgRole
    },
    isOrgRole() {
      return this.$store.getters.isOrgRole
    },
    inShareTips() {
      if (this.isOrgRole) {
        return '贵单位已说明该指标已纳入重点考核，暂无需推送。'
      } else {
        return '请通过共享数据查看证明材料。'
      }
    },
    indOrgs() {
      return this.$store.getters['indPush/indEvaOrgs']
    },
    pushSchemeInfo() {
      return this.$store.getters['indPush/schemeInfo']
    },
    rollbackable() {
      if (this.showPushInner) {
        let inRollbackTime = false
        if (this.pushSchemeInfo && this.pushSchemeInfo.recallStart && this.pushSchemeInfo.recallEnd) {
          const now = new Date()
          const startDate = new Date(this.pushSchemeInfo.recallStart)
          const endDate = new Date(this.pushSchemeInfo.recallEnd)
          if (now >= startDate && now <= endDate) {
            inRollbackTime = true
          }
        }

        return inRollbackTime
      }
      return false
    },
    isSecretInd() {
      if (this.details && this.details.isSecret === '1') {
        return true
      }
      return false
    },
  },
  watch: {
    details(val) {
      if (val) {
        this.buildDisplayData()
      }
    },
  },
  created() {
    if (this.details) {
      this.buildDisplayData()
    }
  },
  mounted() {},
  methods: {
    /**
     * 构建展示结构
     * [{
        "id":"", // 单次推送id
        "isRelateInd":false,
        "header": {
            "title": "",
            "cycle": "",
            "status": "",
            "collapse": "-1,0,1",
        },
        "displaySections": [{
                "title": "",
                "data": [],
            }
        ],
        "postConfig": {
            "multi": {
                "min": 1,
                "max": 1,
                "prefix": "",
            },
            share:{ // 共享指标
            },
            "forms":[],
            "fields": [],
            "fieldData": [],
        },
        "children": [{
                "header": {
                    "title": "",
                    "cycle": "",
                    "status": "",
                    "collapse": "",
                },
                "displaySections": [{
                        "title": "",
                        "data": [],
                    }
                ],
                "postConfig": {
                    "multi": {
                        "min": 1,
                        "max": 1,
                        "prefix": "",
                    },
                    "froms":[], // 提供用于展示表单数据和要提交的数据
                    "fields": [], // 提供表单结构
                    "disabled":false
                },
            }
            ]
            }
        ],
        emptyTips:''

     */
    buildDisplayData() {
      if (!this.details.reportIndexList) {
        return
      }
      this.isRelateInd = false
      this.isOtherRelateInShare = false
      let result = []
      const indList = cloneDeep(this.details.reportIndexList)
      let isSecret = false
      let hasSecretResult = false
      indList.forEach(item => {
        if (item.isSecret) {
          isSecret = (item.isSecret === '1' && true) || false
        }
        if ([INDICATION_STATUS.finished, INDICATION_STATUS.delayFinished].includes(item.status)) {
          hasSecretResult = true
        }
        item.optionFillList.forEach(fieldItem => {
          fieldItem.config = JSON.parse(fieldItem.specificJson)
        })
        item.relateIndexList &&
          item.relateIndexList.forEach((rItem, idx) => {
            if (rItem.optionFillList) {
              rItem.optionFillList.forEach(oItem => {
                oItem.config = JSON.parse(oItem.specificJson)
              })
            }
            if (idx === 0) {
              if ([INDICATION_STATUS.finished, INDICATION_STATUS.delayFinished].includes(rItem.status)) {
                hasSecretResult = true
                isSecret = (rItem.isSecret === '1' && true) || false
              }
            }
          })
      })
      this.isSecret = isSecret
      this.hasSecretResult = hasSecretResult

      if (indList.length) {
        const currInd = indList[0]
        const relateList = currInd.relateIndexList
        const rootRelate = relateList && relateList[0]
        if (rootRelate) {
          this.isRelateInd = true
          result = this.buildRelateInds(indList)
        } else if (this.details.crossDepartList) {
          result = this.buildCrossOrgInd(indList, this.details.crossDepartList)

          if (this.isOrgRole) {
            this.listProvincialOrgan()
          }
        } else {
          result = this.buildSingleInd(indList)
        }
      }
      this.displayList = result
    },
    // 关联指标类型
    // 根指标为唯一推送周期
    buildRelateInds(indList) {
      const currInd = indList[0]
      const relateList = currInd.relateIndexList
      const rootRelate = relateList && relateList[0]
      const relateIndex = relateList.findIndex(item => item.optionId === currInd.optionId)
      // const indFinished = rootRelate.status === INDICATION_STATUS.finished
      const isMultiCycle = indList.length > 1 // 是否是多次推送
      const result = []
      if (relateIndex > 0) {
        // 上个关联指标
        const preInd = relateList[relateIndex - 1]
        // 第一个指标已推送
        const parentList = relateList.filter((rItem, rIdx) => {
          return (
            rIdx < relateIndex && [INDICATION_STATUS.finished, INDICATION_STATUS.delayFinished].includes(rItem.status)
          )
        })
        // 父关联指标已推送
        if (parentList.length === relateIndex) {
          // 移出 fromShare 字段
          if (rootRelate.optionFillList[0].config.type === IND_POST_TYPE.fromShare) {
            const fromShareField = rootRelate.optionFillList.splice(0, 1)
            const fromShareFieldId = fromShareField[0].fillId
            const fromShareWriteData = rootRelate.optionWriteList[0].find(item => {
              return item.fillId === fromShareFieldId
            })
            if (fromShareWriteData) {
              const shareConfig = fromShareWriteData.specificJson && JSON.parse(fromShareWriteData.specificJson)
              const sareMax = (shareConfig && shareConfig.shareMax) || '1'
              if (fromShareWriteData.content === sareMax) {
                this.isOtherRelateInShare = true
                return
              }
            }
          }
          const fromShareInnerField = rootRelate.optionFillList.find(
            oItem => oItem.config.type === IND_POST_TYPE.fromShareInner
          )

          if (fromShareInnerField) {
            const notShareItem = rootRelate.optionWriteList.find(wList => {
              return (
                wList.find(wItem => {
                  return wItem.fillId === fromShareInnerField.fillId && wItem.content === '0'
                }) !== undefined
              )
            })
            if (!notShareItem) {
              this.isOtherRelateInShare = true
              return
            }
          }

          const titleFieldId = rootRelate.optionFillList[1].fillId

          indList.forEach((indItem, indIndex) => {
            const { optionType, status, startTime, endTime, optionFillList, optionWriteList } = indItem
            const itemWriteMulti = optionType === 'write_multiple_choice'

            const children = []
            const header = {
              title: (isMultiCycle && `第 ${indIndex + 1} 次推送`) || '' + '推送内容',
              cycle: formatDate(startTime, 'yyyy-MM-dd') + ' ~ ' + formatDate(endTime, 'yyyy-MM-dd'),
              status: status,
              collapse: (isMultiCycle && 1) || 0,
            }
            result.push({
              id: indItem.id,
              isRelateInd: true,
              header: header,
              indIndex: indIndex,
              children,
            })

            // 根关联指标 表单数量
            rootRelate.optionWriteList.forEach((rootWriteItem, rootWriteIdx) => {
              const writeTitle = rootWriteItem.find(wItem => wItem.fillId === titleFieldId).content

              rootWriteItem.forEach(rItem => {
                rItem.config = parseJsonStr(rItem.specificJson)
              })
              // 1. 构造 parentDisplay
              // root relate 按次序构造
              const parentDisplay = []
              const firstWriteData = this.buildOptionFields(
                rootRelate.optionFillList,
                rootWriteItem.filter(item => item.fillId !== titleFieldId)
              )
              parentDisplay.push({ data: firstWriteData })
              // 其他级别 按 pid 构造
              parentList.slice(1).forEach((item, oIdx) => {
                const oWriteList =
                  (item.optionWriteList &&
                    item.optionWriteList.filter(wItem => {
                      return wItem[0].pidOrder === rootWriteIdx + ''
                    })) ||
                  []

                oWriteList.forEach(wItem => {
                  const writeData = this.buildOptionFields(relateList[oIdx + 1].optionFillList, wItem)
                  parentDisplay.push({ data: writeData })
                })
              })
              // 2. 构造自身展示、构造 postConfig
              const selfDisplay = []
              const pushChildren = null
              let postConfig = null

              if ([INDICATION_STATUS.finished, INDICATION_STATUS.delayFinished].includes(status)) {
                const currWriteList =
                  (optionWriteList &&
                    optionWriteList.filter(item => {
                      return item[0].pidOrder === rootWriteIdx + ''
                    })) ||
                  []
                currWriteList.forEach(item => {
                  selfDisplay.push({ title: indItem.writeTitle, data: this.buildOptionFields(optionFillList, item) })
                })
              } else {
                // 未填报，构造postConfig 和 postData
                let fixedMulti = false
                if (this.multipleMin && this.multipleMin === this.multipleMax) {
                  fixedMulti = true
                }
                let postMulti = null
                if (itemWriteMulti && !fixedMulti) {
                  postMulti = {
                    min: this.multipleMin,
                    max: this.multipleMax,
                    prefix: indItem.writeTitle,
                  }
                }
                let formCount = (postMulti && postMulti.min) || 1

                let fieldData = []
                if (optionWriteList && optionWriteList.length) {
                  // 已填写
                  const currWriteList = optionWriteList.filter(item => {
                    return item[0].pidOrder === rootWriteIdx + ''
                  })
                  formCount = currWriteList.length || formCount
                  fieldData = currWriteList
                }
                const shareItemInner = rootWriteItem.find(
                  rItem => rItem.config && rItem.config.type === IND_POST_TYPE.fromShareInner
                )
                // 内部有share字段，且share为1时，将跳过本次填报
                if (shareItemInner && shareItemInner.content === '1') {
                  formCount = 0
                }
                const forms = []
                // 构造 postData
                for (let i = 0; i < formCount; i++) {
                  forms.push({
                    id: guid(),
                    pid: preInd.optionId,
                    pidOrder: rootWriteIdx,
                    pushId: indItem.id,
                    data: null,
                    fieldData: fieldData[i] || [],
                  })
                }
                postConfig = {
                  share: this.buildShareField(optionFillList, optionWriteList),
                  multi: postMulti,
                  forms: forms,
                  fields: optionFillList,
                  pushId: indItem.id,
                  pid: preInd.optionId, // 关联指标上级id
                  pidOrder: rootWriteIdx, // 根指标 order
                  disabled: !this.pushable || indItem.status === INDICATION_STATUS.notStart,
                }
              }

              children.push({
                header: {
                  title: writeTitle,
                },
                displaySections: [...parentDisplay, ...selfDisplay],
                postConfig: postConfig,
                children: pushChildren,
              })
            })
          })
        } else {
          // 父关联指标未推送时候展示单个指标推送信息
          return this.buildSingleInd(indList, true, true)
        }
      } else {
        return this.buildSingleInd(indList, false, true)
      }
      return result
    },
    // 跨部门评价指标
    buildCrossOrgInd(indList, orgConfig) {
      const result = []
      const isMultiCycle = indList.length > 1 // 是否是多次推送
      indList.forEach((indItem, indIndex) => {
        const { optionType, status, startTime, endTime, optionFillList, optionWriteList, writeTitle } = indItem
        const itemWriteMulti = optionType === 'write_multiple_choice'
        const header = {
          title: (isMultiCycle && `第 ${indIndex + 1} 次推送`) || '' + '推送内容',
          cycle: formatDate(startTime, 'yyyy-MM-dd') + ' ~ ' + formatDate(endTime, 'yyyy-MM-dd'),
          status: status,
          collapse: (isMultiCycle && 1) || 0,
        }

        // 部门评价方式放入 children中
        const children = []
        orgConfig.forEach((orgConfigItem, orgConfigIdx) => {
          const cHeader = {
            title: orgConfigItem.name,
            collapse: (orgConfig.length > 1 && 1) || 0,
          }
          let displaySections = null
          let postConfig = null
          const finished =
            [INDICATION_STATUS.finished, INDICATION_STATUS.delayFinished].includes(status) && optionWriteList
          if (finished) {
            // optionWriteList 为双层数组
            displaySections = []
            optionWriteList.forEach((writeItem, wIdx) => {
              if (writeItem[0].pid === orgConfigItem.code) {
                displaySections.push({
                  title: (itemWriteMulti && `${writeTitle}${wIdx + 1}`) || null,
                  data: this.buildOptionFields(optionFillList, writeItem),
                })
              }
            })
          } else {
            let postMulti = null
            if (itemWriteMulti) {
              postMulti = {
                min: this.multipleMin,
                max: this.multipleMax,
                prefix: writeTitle,
              }
            }
            let forms = []
            let orgWriteList = []
            if (optionWriteList) {
              orgWriteList = optionWriteList.filter(item => {
                return item[0].pid === orgConfigItem.code
              })
              forms = orgWriteList.map((wItem, wIdx) => ({
                id: guid(),
                data: null,
                pid: orgConfigItem.code,
                pidOrder: orgConfigIdx,
                pushId: indItem.id,
                fieldData: orgWriteList[wIdx],
              }))
            }
            if (forms.length === 0) {
              forms = [
                {
                  id: guid(),
                  data: null,
                  pid: orgConfigItem.code,
                  pidOrder: orgConfigIdx,
                  pushId: indItem.id,
                  fieldData: [],
                },
              ]
            }
            postConfig = {
              share: null,
              multi: postMulti,
              fields: optionFillList,
              disabled: !this.pushable || indItem.status === '0',
              pid: orgConfigItem.code,
              pidOrder: orgConfigIdx,
              pushId: indItem.id,
              forms: forms,
            }
          }
          children.push({
            header: cHeader,
            indIndex: indIndex,
            postConfig,
            displaySections,
            emptyTips: (finished && displaySections.length === 0 && '未选择评价单位') || '',
          })
        })
        result.push({
          id: indItem.id,
          header,
          children,
        })
      })
      return result
    },
    // 没有关联指标项（或关联指标的根指标）
    buildSingleInd(indList, disabled, isRelateInd) {
      const result = []
      const isMultiCycle = indList.length > 1 // 是否是多次推送

      const postMaxCount = this.multipleMax || 1 // 多表单
      let fixedMulti = false
      if (this.multipleMin && this.multipleMin === this.multipleMax) {
        fixedMulti = true
      }

      indList.forEach((indItem, indIndex) => {
        const { optionType, status, startTime, endTime, optionFillList, optionWriteList, writeTitle } = indItem
        const itemWriteMulti = optionType === 'write_multiple_choice'

        const header = {
          title: (isMultiCycle && `第 ${indIndex + 1} 次推送`) || '' + '推送内容',
          cycle: formatDate(startTime, 'yyyy-MM-dd') + ' ~ ' + formatDate(endTime, 'yyyy-MM-dd'),
          status: status,
          collapse: (isMultiCycle && 1) || 0,
        }
        // 单个推送周期内-单个表单

        let displaySections = null
        let postConfig = null
        if ([INDICATION_STATUS.finished, INDICATION_STATUS.delayFinished].includes(status)) {
          // optionWriteList 为双层数组（对应多表单情况）
          displaySections = []
          optionWriteList &&
            optionWriteList.forEach((writeItem, wIdx) => {
              displaySections.push({
                title: (itemWriteMulti && `${writeTitle}${wIdx + 1}`) || null,
                data: this.buildOptionFields(optionFillList, writeItem),
              })
            })
        } else {
          let formInitCount = this.multipleMin || 1
          if (fixedMulti) {
            formInitCount = postMaxCount
          }
          if (optionWriteList && optionWriteList.length) {
            if (formInitCount < optionWriteList.length) {
              formInitCount = optionWriteList.length
            }
          }
          let postMulti = null
          if (itemWriteMulti && !fixedMulti) {
            // 不是固定form数量时，配置 multi
            postMulti = {
              min: this.multipleMin,
              max: this.multipleMax,
              prefix: indItem.writeTitle,
              disabled: !this.pushable || indItem.status === '0',
            }
          }
          const forms = []
          for (let i = 0; i < formInitCount; i++) {
            forms.push({
              id: guid(),
              pushId: indItem.id,
              data: null,
              fieldData: (optionWriteList && optionWriteList[i]) || [],
            })
          }
          postConfig = {
            share: this.buildShareField(optionFillList, optionWriteList),
            fields: optionFillList,
            disabled: !this.pushable || disabled || indItem.status === '0',
            pushId: indItem.id,
            forms,
            multi: postMulti,
          }
        }
        console.log('%c⧭', 'color: #364cd9', this.isSecretInd, postConfig)
        if (this.isSecretInd && indIndex === 0) {
          this.secretDisabled = postConfig?.disabled
          console.log('%c⧭', 'color: #364cd9', this.secretDisabled)
        }
        result.push({
          id: indItem.id,
          isRelateInd: isRelateInd,
          header: header,
          indIndex: indIndex,
          displaySections,
          postConfig,
        })
      })
      return result
    },
    // 匹配选项与作答
    buildOptionFields(fields, fieldWrites) {
      const results = []
      fields.forEach(oItem => {
        const vItem = fieldWrites.find(vItem => vItem.fillId === oItem.fillId)
        if (vItem) {
          results.push({
            fillId: oItem.fillId,
            title: oItem.title,
            config: (oItem.specificJson && JSON.parse(oItem.specificJson)) || '',
            content: vItem.busContent || vItem.content,
            fileShowList: vItem.fileShowList,
          })
        }
      })
      return results
    },
    buildPostData(list, isInnerForm) {
      const forms = (!isInnerForm && this.getForms(list)) || list
      // froms 按pushId 分组
      const pushGroups = []
      forms.forEach(fItem => {
        const { pushId, data, share } = fItem
        let groupItem = pushGroups.find(gItem => gItem.id === pushId)
        if (!groupItem) {
          groupItem = {
            id: pushId,
            optionFillList: [],
          }
          pushGroups.push(groupItem)
        }
        const fieldArr = []
        if (data) {
          for (const id in data) {
            const val = data[id].value
            const config = data[id].config
            // 文件类型
            if (config.type === IND_POST_TYPE.file) {
              fieldArr.push({
                fillId: id,
                fileShowList: val,
                pid: fItem.pid, // 关联指标上级id
                pidOrder: fItem.pidOrder, // 关联指标上级order
                orderBy: groupItem.optionFillList.length,
              })
            } else {
              fieldArr.push({
                fillId: id,
                content: val,
                pid: fItem.pid,
                pidOrder: fItem.pidOrder,
                orderBy: groupItem.optionFillList.length,
              })
            }
          }
        } else if (share) {
          fieldArr.push({
            fillId: share.fillId,
            content: share.value,
            pid: null,
            pidOrder: null,
            orderBy: 0,
          })
        }
        groupItem.optionFillList.push(fieldArr)
      })
      return pushGroups
    },
    buildShareField(fields, fieldWrites) {
      const shareField = fields.find(fItem => {
        return fItem.config.type === IND_POST_TYPE.fromShare
      })
      if (shareField) {
        let writeContent = 0
        if (fieldWrites && fieldWrites.length) {
          const writeData = fieldWrites[0].find(wItem => {
            return wItem.fillId === shareField.fillId
          })
          if (writeData && writeData.content) {
            writeContent = Number(writeData.content)
          }
        }
        return {
          title: shareField.title,
          fillId: shareField.fillId,
          config: shareField.config,
          value: writeContent,
        }
      }
      return null
    },
    getForms(list) {
      let forms = []
      list.forEach(item => {
        if (item.postConfig && !item.postConfig.disabled) {
          forms = [
            ...forms,
            ...item.postConfig.forms.map(fItem => {
              return {
                ...fItem,
                share: item.postConfig && item.postConfig.share,
              }
            }),
          ]
        }
        if (item.children) {
          const childForms = this.getForms(item.children)
          forms = [...forms, ...childForms]
        }
      })
      return forms
    },
    getPostForms(list) {
      let forms = []
      list.forEach(item => {
        if (item.postConfig && !item.postConfig.disabled) {
          const childForms = item.postConfig.forms.map(fItem => {
            return {
              share: item.postConfig.share,
              multi: item.postConfig.multi,
              ...fItem,
            }
          })
          forms = [...forms, ...childForms]
        }
        if (item.children) {
          const childForms = this.getPostForms(item.children)
          forms = [...forms, ...childForms]
        }
      })
      return forms
    },
    listProvincialOrgan() {
      if (!this.indOrgs || this.indOrgs.length === 0) {
        listProvincialOrgan().then(res => {
          if (res.code === 0) {
            const resData = res.data
            const orgs = resData.map(item => ({
              label: item.orgName,
              value: item.id,
            }))
            const orgId = localStorage.getItem('orgId')
            if (orgId) {
              // 去除掉本单位
              this.$store.commit(
                'indPush/setIndEvaOrgs',
                orgs.filter(item => item.value !== orgId)
              )
            } else {
              this.$store.commit('indPush/setIndEvaOrgs', orgs)
            }
          }
        })
      }
    },
    saveFormAuto() {
      const postArr = this.buildPostData(this.displayList)
      this.$store.dispatch('indPush/saveIndicationTempBatch', {
        id: this.details.optionId,
        postData: postArr,
        isSecret: this.isSecret,
      })
    },
    // 批量保存或指定ind保存
    saveFormData(isSubmit = false, indItem) {
      let toSaveList = this.displayList
      let isSaveBatch = true
      if (indItem) {
        toSaveList = [indItem]
        isSaveBatch = false
      }
      this.formValid.check = false

      let isAllShare = false
      // 非空校验
      if (isSubmit && !this.isSecret) {
        // 跨部门评价可以只提交牵头或配合的数据，单独处理
        if (this.details.crossDepartList) {
          // 跨部门评价，默认评分都会有值，判断是否选择了单位，如果没有选择单位，将该条数据过滤掉

          // 要评价的协同单位 froms
          const xtForms = toSaveList[0].children[0].postConfig.forms

          // 要评价的牵头单位 froms
          const qtForms = toSaveList[0].children[1].postConfig.forms

          // 使用index判断，防止字段名变化
          const xtOrgFiledId = toSaveList[0].children[0].postConfig.fields[0].fillId
          const qtOrgFiledId = toSaveList[0].children[1].postConfig.fields[0].fillId

          const xtEvaFiledId = toSaveList[0].children[0].postConfig.fields[2].fillId
          const qtEvaFiledId = toSaveList[0].children[1].postConfig.fields[2].fillId

          const xtSaveForms = xtForms.filter(item => item.data[xtOrgFiledId].value !== '')
          const qtSaveForms = qtForms.filter(item => item.data[qtOrgFiledId].value !== '')

          if (xtSaveForms.length === 0 && qtSaveForms.length === 0) {
            this.$message.warning('请先选择要评价的单位，再提交数据！')
          } else {
            const xtInvalidForms = xtForms.filter(
              item => item.data[xtOrgFiledId].value === '' && item.data[xtEvaFiledId].value !== ''
            )
            const qtInvalidForms = qtForms.filter(
              item => item.data[qtOrgFiledId].value === '' && item.data[qtEvaFiledId].value !== ''
            )
            if (xtInvalidForms.length || qtInvalidForms.length) {
              this.$message.warning('已填写的评语中，有未选择的单位！')
              const emptyForm = xtInvalidForms[0] || qtInvalidForms[0]
              this.$nextTick(() => {
                this.formValid.scope = emptyForm.id
                this.formValid.check = true
              })
              return
            }

            const postArr = this.buildPostData([...xtSaveForms, ...qtSaveForms], true)
            if (xtSaveForms.length === 0 || qtSaveForms.length === 0) {
              let emptyTips = '只填写了对协同单位的评价'
              if (qtSaveForms.length !== 0) {
                emptyTips = '只填写了对牵头单位的评价'
              }
              this.$confirm(`${emptyTips}，确定要提交该指标?`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
              })
                .then(() => {
                  this.postSaveData(postArr, isSubmit)
                })
                .catch(() => {})
            } else {
              this.postSaveData(postArr, isSubmit)
            }
          }
          return
        } else {
          const postForms = this.getPostForms(toSaveList)
          const emptyForm = postForms.find(item => {
            const fieldData = item.data
            if (fieldData) {
              let hasEmpty = false
              for (const id in fieldData) {
                const val = fieldData[id].value
                const config = fieldData[id].config
                // 必填
                if (config.isWrite === '1') {
                  if (val === undefined || val.length === 0) {
                    hasEmpty = true
                    break
                  }
                }
              }
              return hasEmpty
            } else {
              return true
            }
          })
          let hasEmpty = emptyForm !== undefined

          if (emptyForm) {
            // from share 时，检查 share value 是否达到了最大限制，达到最大限制时，忽略该必填项
            if (emptyForm.share) {
              if (emptyForm.multi) {
                if (emptyForm.multi.max && emptyForm.multi.max <= emptyForm.share.value) {
                  hasEmpty = false
                }
                if (emptyForm.multi.max && emptyForm.multi.max === emptyForm.share.value) {
                  isAllShare = true
                }
              } else if (emptyForm.share.value === 1) {
                hasEmpty = false
              }
            }
          }

          if (hasEmpty) {
            this.$message.warning('请检查必填项！')
            this.$nextTick(() => {
              this.formValid.scope = (isSaveBatch && 'all') || emptyForm.id
              this.formValid.check = true
            })
            return
          }
        }
      }
      const postArr = this.buildPostData(toSaveList)
      if (isSubmit) {
        this.$confirm('确定要提交该指标?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.postSaveData(postArr, isSubmit, isAllShare)
          })
          .catch(() => {})
      } else {
        this.postSaveData(postArr, isSubmit)
      }
    },
    postSaveData(postArr, isSubmit, isAllShare) {
      if (isSubmit) {
        saveIndPushDataBatch(this.details.optionId, postArr, this.isSecret).then(res => {
          if (res.code === 0) {
            // 刷新当前条目
            // 判断是否是关联指标根节点，且根节点为共享已完成
            this.$emit('submit', isAllShare)
            this.$message.success('提交成功！')
          }
        })
      } else {
        saveIndPushDataTempBatch(this.details.optionId, postArr, this.isSecret).then(res => {
          if (res.code === 0) {
            this.$message.success('暂存成功！')
          }
        })
      }
    },
    rollbackSecretIndPost() {
      this.$confirm('确定要撤回该本次填报吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          const pushId = this.details.reportIndexList[0].id
          rollbackIndPost(pushId).then(res => {
            if (res.code === 0) {
              this.$message.success('撤回成功！')
              this.$emit('rollback', this.details.reportIndexList[0].relateIndexList?.length > 0)
            }
          })
        })
        .catch(() => {})
    },
  },
}
</script>
<style lang="scss" scoped>
.ind-post-view {
  .secret-view {
    background: #fff;
    padding: 16px 30px;
    border: 1px solid #ebeef5;
    font-size: 16px;
    line-height: 26px;
    color: #333;
    .label {
      margin-right: 30px;
    }
    .tips {
      margin-left: 30px;
      color: #e6a23c;
    }
    .kh-return {
      margin-left: 10px;
      padding: 2px;
      color: #fff;
      background: #e6a23c;
      border-radius: 50%;
      cursor: pointer;
    }
  }
  .post-btn-view {
    text-align: center;
    margin: 20px 0;
    .el-button {
      width: 100px;
    }
  }
  .inshare-tips {
    padding: 20px;
    text-align: center;
    color: #f56c6c;
    font-size: 16px;
  }
}
</style>
